#!/usr/autodesk/maya/bin/mayapy
import sys, os
try:
    os.environ['MAYA_MODULE_PATH'] = '/mnt/jiuqian_tools/maya' + ':' + os.environ['MAYA_MODULE_PATH']
except:
    os.environ['MAYA_MODULE_PATH'] = '/mnt/jiuqian_tools/maya'


import pymel.core as pmc
import maya.cmds as cmds
from mtoa.callbacks import *
from arnold import *
import mtoa.core as core
import xgenm as xg
import xgenm.xmaya.xgmExternalAPI as xgmExternalAPI

pmc.loadPlugin('mtoa', quiet=True)
pmc.loadPlugin('xgenToolkit', quiet=True)


def export_ass(filePath):

    shotPath = pmc.Path(filePath)
    pmc.openFile(shotPath)

    # Set startFrame & endFrame
    strat_frame = float(pmc.playbackOptions(q=1, min=1))
    end_frame = float(pmc.playbackOptions(q=1, max=1))
    # Set Filepath & name
    file_name = pmc.sceneName().basename()
    file_path = str(pmc.sceneName())
    file_dir = pmc.sceneName().dirname()
    # Set exportpath
    export_dir = file_dir + r'/assetsASS/'
    # Get all AihairShaders
    allAishader = pmc.ls(type='aiStandardHair')
    # Get all Shadergroup
    shadinggroup = pmc.listConnections(allAishader, type='shadingEngine')
    all = pmc.listConnections(shadinggroup, sh=True)
    oldxgen_exist = None
    for i in all:
        if i.type() == 'xgmDescription':
            oldxgen_exist = True
    print oldxgen_exist

    strScenePath = ''
    if oldxgen_exist == True:
        strCurrentScene = cmds.file(q=True, sn=True)
        strSceneName = ""
        if strCurrentScene:
            strScenePath = os.path.dirname(strCurrentScene)
            strSceneFile = os.path.basename(strCurrentScene)
            strSceneName = os.path.splitext(strSceneFile)[0];
        else:
            xg.XGError(maya.stringTable['y_xgDescriptionEditor.kYouMustSaveTheSceneFirst'])

        ExportStartFrame = float(pmc.playbackOptions(q=1, min=1))
        ExportEndFrame = float(pmc.playbackOptions(q=1, max=1))
        cmdAlembicBase = 'AbcExport -j "'
        # Anim = dialog.getAnim()

        cmdAlembicBase = cmdAlembicBase + '-frameRange ' + str(ExportStartFrame) + ' ' + str(ExportEndFrame)
        cmdAlembicBase = cmdAlembicBase + ' -uvWrite -attrPrefix xgen -worldSpace'
        palette = cmds.ls(exactType="xgmPalette")
        for p in range(len(palette)):
            filename = strScenePath + "/" + strSceneName + "__" + xgmExternalAPI.encodeNameSpace(str(palette[p])) + ".abc"
            descShapes = cmds.listRelatives(palette[p], type="xgmDescription", ad=True)
            cmdAlembic = cmdAlembicBase
            for d in range(len(descShapes)):
                descriptions = cmds.listRelatives(descShapes[d], parent=True)
                if len(descriptions):
                    patches = xg.descriptionPatches(descriptions[0])
                    for patch in patches:
                        cmd = 'xgmPatchInfo -p "' + patch + '" -g';
                        geom = pmc.mel.eval(cmd)
                        geomFullName = cmds.ls(geom, l=True)
                        cmdAlembic += " -root " + geomFullName[0]

            cmdAlembic = cmdAlembic + ' -stripNamespaces -file \'' + filename + '\'";';
            print cmdAlembic
            print 'export xgen patches ...'
            pmc.mel.eval(cmdAlembic)
    allshadingengine = pmc.ls(type='shadingEngine')
    a = pmc.ls(type='xgmDescription') + pmc.ls(type='xgmSplineDescription')
    all_xgen_shadingengine = pmc.listConnections(a, type='shadingEngine')
    solve = []
    for i in all_xgen_shadingengine:
        if not i in solve:
            solve.append(i)
    print solve
    for shading in solve:
        mmm = [x for x in pmc.listConnections(shading, type=["xgmDescription", "xgmSplineDescription"]) if x.isVisible()]
        if mmm:
            pmc.select(mmm)
            pmc.arnoldExportAss(s=True, ep=False, f=export_dir + shading + 'Ass', m=8)
    print "export path to" + export_dir + shading + 'Ass'
    print "DOne...!"



if __name__ == '__main__':

    import maya.standalone
    maya.standalone.initialize()
    if os.path.exists(sys.argv[1]) and os.path.isfile(sys.argv[1]):
        export_ass(sys.argv[1])

    maya.standalone.uninitialize()
